
#include "Particle.h"
#include "../../Utils/Timer.h"
#include "../../Utils/Util.h"
#include "../TextureManager.h"

#include <GL/gl.h>
#include <cmath>

Particle::Particle(float col_r, float col_g, float col_b,
                   float life, float size, float life_decay, float size_decay,
                   Vector2D position, Vector2D velocity,
                   bool use_texturing, unsigned texture_id,
                   bool flare_up):
 
    col_r(col_r), col_g(col_g), col_b(col_b),
    life(life), size(size), life_decay(life_decay), size_decay(size_decay),
    position(position), velocity(velocity),
    use_texturing(use_texturing), texture_id(texture_id),
    flare_up(flare_up) {

    if(flare_up){ 
        life_inc = true; 
        life = 0.0f; 
        cur_size = 0.0f;
    }
    else{
        cur_size = size;
    }
}

Particle::~Particle(){

}
    
void Particle::render(void){
    if(use_texturing){
        glEnable(GL_TEXTURE_2D);
        TextureManager::instance().bindTexture(texture_id);
    }

    glColor4f(col_r, col_g, col_b, life);

    glBegin(GL_QUADS);
      glTexCoord2f(0.0f, 0.0f);
      glVertex3f(position.x+cur_size/2.0f, position.y+cur_size/2.0f, 0.0f);
    
      glTexCoord2f(0.0f, 1.0f);
      glVertex3f(position.x+cur_size/2.0f, position.y-cur_size/2.0f, 0.0f);
    
      glTexCoord2f(1.0f, 1.0f);
      glVertex3f(position.x-cur_size/2.0f, position.y-cur_size/2.0f, 0.0f);
    
      glTexCoord2f(1.0f, 0.0f);
      glVertex3f(position.x-cur_size/2.0f, position.y+cur_size/2.0f, 0.0f);
    glEnd();


    if(use_texturing){
        glDisable(GL_TEXTURE_2D);
    }
}

void Particle::update(void){
    position.add(Timer::secondsSinceLastFrame()*velocity);

    size -= size_decay * Timer::secondsSinceLastFrame();

    if(flare_up && life_inc){
        life += 2.0f*life_decay*Timer::secondsSinceLastFrame();
        cur_size = size*life*4.0f;
        if(cur_size > size){ cur_size = size; }

        if(life > 1.0f){ life_inc = false; }
    }
    else{
        life -= life_decay*Timer::secondsSinceLastFrame();
    }
}

bool Particle::active(void){
    return life >= 0.0f;
}

